package com.koron.system.app.service.impl;

import com.koron.bean.app.AppBean;
import com.koron.bean.base.BaseQueryBean;
import com.koron.bean.system.role.RoleBean;
import com.koron.bean.system.role.UserOwnJurisdictionBean;
import com.koron.bean.system.staff.vo.EamUser;
import com.koron.bean.util.UUIDUtils;
import com.koron.common.core.business.datadict.utils.DataDictTool;
import com.koron.common.core.config.ThreadLocalContext;
import com.koron.system.app.mapper.AppMapper;
import com.koron.system.app.service.AppService;
import com.koron.system.redis.RedisPublisher;
import com.koron.system.staff.service.StaffService;
import org.apache.commons.collections4.CollectionUtils;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.Date;
import java.util.List;
import java.util.Map;
import java.util.Objects;

/**
 * @ClassName AppServiceImpl
 * @description
 * @Author zhouj
 * @Date 2021/7/13 10:39
 */
@Transactional
@Service
public class AppServiceImpl implements AppService {

    @Autowired
    AppMapper appMapper;

    @Autowired
    StaffService staffService;

    @Autowired
    RedisPublisher redisPublisher;

    private String getDbUrlPrefix() {
        Map<String, String> dataDictByCode = DataDictTool.getDataDictByCode("systemManagement", "db_url");
        return dataDictByCode.getOrDefault("prefix", "");
    }

    private String getDbUrlSuffix() {
        Map<String, String> dataDictByCode = DataDictTool.getDataDictByCode("systemManagement", "db_url");
        return dataDictByCode.getOrDefault("suffix", "");
    }

    @Override
    public int inUpApp(AppBean appBean, EamUser user) {
        int i = 0;
        if (StringUtils.isEmpty(appBean.getId())) {
            appBean.setId(UUIDUtils.getUuid());
            appBean.setCreateBy(user.getAccount());
            appBean.setCreateByName(user.getName());
            appBean.setCreateTime(new Date());
            appBean.setDbFullHost(dealDbUrl(appBean));
            i = appMapper.insert(appBean);
            redisPublisher.publish(appBean);
        }
        return i;
    }

    private String dealDbUrl(AppBean appBean) {

        StringBuilder sb = new StringBuilder();
        sb.append(getDbUrlPrefix())
                .append(appBean.getDbHost())
                .append(":")
                .append(appBean.getDbPort())
                .append("/")
                .append(appBean.getDbName())
                .append(getDbUrlSuffix());
        return sb.toString();

    }

    @Override
    public int updateApp(AppBean appBean, EamUser user) {
        int i = 0;
        if (!StringUtils.isEmpty(appBean.getId())) {
            appBean.setUpdateBy(user.getAccount());
            appBean.setUpdateByName(user.getName());
            appBean.setUpdateTime(new Date());
            appBean.setDbFullHost(dealDbUrl(appBean));
            i = appMapper.update(appBean);
            redisPublisher.publish(appBean);

        }
        return i;
    }

    @Override
    public int deleteApp(String id) {
        int i = appMapper.softDelete(id);
        //清空 用户的默认租户
        staffService.clearDefaultAppId(id);
        AppBean appBean = new AppBean();
        appBean.setId(id);
        redisPublisher.publish(appMapper.querySingleApp(appBean));
        return i;
    }

    @Override
    public int deleteAppList(List<String> ids) {
        return appMapper.deleteAppList(ids);
    }

    @Override
    public List<AppBean> queryAppList(AppBean appBean, BaseQueryBean queryBean) {
        List<AppBean> appBeanList = appMapper.queryAppList(appBean, queryBean);
        if (CollectionUtils.isNotEmpty(appBeanList)) {
            appBeanList.forEach(p -> {
                p.setDbPassword(null);
                p.setDbDriverClassName(null);
                p.setDbPort(null);
                p.setDbHost(null);
                p.setDbUser(null);
                p.setDbFullHost(null);
                p.setDbName(null);
            });
        }
        return appBeanList;
    }

    @Override
    public Long queryAppListCount(AppBean appBean) {
        return appMapper.queryAppListCount(appBean);
    }

    @Override
    public AppBean querySingleApp(AppBean appBean) {
        AppBean appBean1 = appMapper.querySingleApp(appBean);
        if (Objects.isNull(appBean1) || !isSuperAdmin()) {
            appBean1.setDbPassword(null);
        }
        return appMapper.querySingleApp(appBean);
    }

    @Override
    public int startOrStopApp(List<String> ids, Integer status) {
        return appMapper.startOrStopApp(ids, status);
    }

    public Boolean isSuperAdmin() {
        UserOwnJurisdictionBean userOwnJurisdictionBean = ThreadLocalContext.get().getUserOwnJurisdictionBean();
        if (!Objects.isNull(userOwnJurisdictionBean)) {
            List<RoleBean> roleBean = userOwnJurisdictionBean.getRoleBean();
            if (CollectionUtils.isNotEmpty(roleBean)) {
                for (RoleBean bean : roleBean) {
                    if ("role_root".equals(bean.getRoleType())) {
                        return true;
                    }
                }
            }
        }
        return false;
    }

}
